<?php 
/**
 * multivendor.php
 *
 * Multi vendor registration management
 *
 * @author     Makai Lajos
 * @copyright  2015
 * @license    License.txt
 * @version    2.0
 * @link       http://opencart-api.com/product/opencart-restful-api-pro-v2-0/
 * @see        http://newapi2.opencart-api.com/demo/
 */
require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerRestMultivendor extends RestController {

	private $error = array();

	public function registerCustomer($data) {

		$json = array('success' => true);

		// Validate if customer is logged in.
		if ($this->customer->isLogged()) {
			$json['error']		= "User already is logged";	
			$json['success'] = false;
		}

		$this->language->load('account/signup');
		$this->load->model('account/signup');

		if ( $this->validate($data) && ($this->config->get('mvd_sign_up'))) {
			
			$data['agree'] = true;			

			if ($this->config->get('mvd_paypal_status')) {
				$data['mvd_paypal_status'] = true;
			} else {
				$data['mvd_paypal_status'] = false;
			}

			if ($this->config->get('mvd_bank_status')) {
				$data['mvd_bank_status'] = true;
			} else {
				$data['mvd_bank_status'] = false;
			}

			if(!isset($data['payment_method'])){
				if ($data['mvd_paypal_status'] && !$data['mvd_bank_status']) {
					$data['payment_method'] = 1;
				} else if (!$data['mvd_paypal_status'] && $data['mvd_bank_status']) {
					$data['payment_method'] = 0;
				} else {
					$data['payment_method'] = $this->config->get('mvd_signup_default_payment_method');
				}
			}

			
			if ($data['singup_plan'] != "") {
				$singup_plan = explode(':',$data['singup_plan']);
				if (($singup_plan[1] == '4' || $singup_plan[1] == '5') && ($data['payment_method'])) {
					$this->model_account_signup->addVendorSignUp($data);
					if (!file_exists(rtrim(DIR_IMAGE . 'catalog/', '/') . '/' . str_replace('../', '', $data['username']))) {
						mkdir(rtrim(DIR_IMAGE . 'catalog/', '/') . '/' . str_replace('../', '', $data['username']), 0777);
					}
					$json['paypal_url'] = $this->send($data);
				} elseif (($singup_plan[1] == '4' || $singup_plan[1] == '5') && (!$data['payment_method'])) {
					$this->model_account_signup->addVendorSignUp($data);
					if (!file_exists(rtrim(DIR_IMAGE . 'catalog/', '/') . '/' . str_replace('../', '', $data['username']))) {
						mkdir(rtrim(DIR_IMAGE . 'catalog/', '/') . '/' . str_replace('../', '', $data['username']), 0777);
					}
				} else {
					if ($this->config->get('mvd_signup_auto_approval')) {
						if (!file_exists(rtrim(DIR_IMAGE . 'catalog/', '/') . '/' . str_replace('../', '', $data['username']))) {
							mkdir(rtrim(DIR_IMAGE . 'catalog/', '/') . '/' . str_replace('../', '', $data['username']), 0777);
						}
					}
					$this->model_account_signup->addVendorSignUp($data);
				}
			} else {
				if ($this->config->get('mvd_signup_auto_approval')) {
					if (!file_exists(rtrim(DIR_IMAGE . 'catalog/', '/') . '/' . str_replace('../', '', $data['username']))) {
						mkdir(rtrim(DIR_IMAGE . 'catalog/', '/') . '/' . str_replace('../', '', $data['username']), 0777);
					}
				}
				$this->model_account_signup->addVendorSignUp($data);
			}
		} else {
			$json["success"] = false;
			$json['error'] = $this->error;
		}

		return $this->sendResponse($json);
	}

	private function validate($data) {
		if ($this->model_account_signup->getUsernameBySignUp($data['username'])) {
			$this->error['warning'] = $this->language->get('error_username_exists');
		}

		if ($this->model_account_signup->getEmailBySignUp($data['email'])) {
			$this->error['warning'] = $this->language->get('error_exists');
		}


		if ((utf8_strlen($data['username']) < 1) || (utf8_strlen($data['username']) > 32)) {
			$this->error['username'] = 'Username must be between 1 and 32 characters!';
		}

		if ((utf8_strlen($data['firstname']) < 1) || (utf8_strlen($data['firstname']) > 32)) {
			$this->error['firstname'] = $this->language->get('error_firstname');
		}

		if ((utf8_strlen($data['lastname']) < 1) || (utf8_strlen($data['lastname']) > 32)) {
			$this->error['lastname'] = $this->language->get('error_lastname');
		}

		if ((utf8_strlen($data['email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $data['email'])) {
			$this->error['email'] = $this->language->get('error_email');
		}

		if (!empty($data['paypal'])) {
			if ((utf8_strlen($data['paypal']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $data['paypal'])) {
				$this->error['paypal'] = $this->language->get('error_paypal');
			}
		}

		if ((utf8_strlen($data['telephone']) < 3) || (utf8_strlen($data['telephone']) > 32)) {
			$this->error['telephone'] = $this->language->get('error_telephone');
		}

		if ((utf8_strlen($data['address_1']) < 3) || (utf8_strlen($data['address_1']) > 128)) {
			$this->error['address_1'] = $this->language->get('error_address_1');
		}

		if ((utf8_strlen($data['city']) < 2) || (utf8_strlen($data['city']) > 128)) {
			$this->error['city'] = $this->language->get('error_city');
		}

		if ((utf8_strlen($data['company']) < 2) || (utf8_strlen($data['company']) > 128)) {
			$this->error['company'] = $this->language->get('error_company');
		}

		$this->load->model('localisation/country');

		$country_info = $this->model_localisation_country->getCountry($data['country_id']);

		if ($country_info && $country_info['postcode_required'] && (utf8_strlen($data['postcode']) < 2) || (utf8_strlen($data['postcode']) > 10)) {
			$this->error['postcode'] = $this->language->get('error_postcode');
		}

		if ($data['country_id'] == '') {
			$this->error['country'] = $this->language->get('error_country');
		}

		if ($data['zone_id'] == '') {
			$this->error['zone'] = $this->language->get('error_zone');
		}

		if ((utf8_strlen($data['password']) < 4) || (utf8_strlen($data['password']) > 20)) {
			$this->error['password'] = $this->language->get('error_password');
		}

		if ($data['confirm'] != $data['password']) {
			$this->error['confirm'] = $this->language->get('error_confirm');
		}

		if ($this->config->get('config_account_id')) {
			$this->load->model('catalog/information');

			$information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));
			if ($information_info && !isset($data['agree'])) {
				$this->error['warning'] = sprintf($this->language->get('error_agree'), $information_info['title']);
			}
		}

		if (!$this->error) {
			return true;
		} else {
			return false;
		}
	}


	public function send($post) {

		$this->language->load('account/signup');
		$this->load->model('account/signup');

		$custom_id = $this->model_account_signup->getUserID($post['username']);

		$splan = explode(':',$post['singup_plan']);
		$signup_amount = $this->model_account_signup->getSignUpRate($splan[0],$splan[1]);

		$request = 'cmd=_xclick';
		$request .= '&business=' . $this->config->get('mvd_signup_paypal_email');
		$request .= '&item_name=' . html_entity_decode($this->language->get('text_signup_plan') . $post['hsignup_plan'], ENT_QUOTES, 'UTF-8');
		$request .= '&notify_url=' . $this->url->link('account/signup_callback/signup_callback', '', 'SSL');
		$request .= '&cancel_return=' . $this->url->link('account/signup', '', 'SSL');
		$request .= '&return=' . $this->url->link('account/signupsuccess');
		$request .= '&currency_code=' . $this->config->get('config_currency');
		$request .= '&amount=' . $signup_amount;
		$request .= '&custom=' . $custom_id;

		$url = "";
		if ($this->config->get('mvd_signup_paypal_sandbox')) {
			$url = 'https://www.sandbox.paypal.com/cgi-bin/webscr?' . $request;
		} else {
			$url = 'https://www.paypal.com/cgi-bin/webscr?' . $request;
		}

		return $url;
	}
	
	public function register() {

		$this->checkPlugin();

		if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
			//add new customer
			$requestjson = file_get_contents('php://input');
		
			$requestjson = json_decode($requestjson, true);           

			if (!empty($requestjson)) {
				$this->registerCustomer($requestjson);
			}else {
				$this->response->setOutput(json_encode(array('success' => false)));
			}
		}else {
				$json["error"]		= "Only POST request method allowed";
				$json["success"]	= false;

			return $this->sendResponse($json);
		}    
    }

	public function infos() {

		$this->checkPlugin();

		if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
			$this->load->model('account/signup');

			$json["success"]	= true;
			$list = $this->model_account_signup->getCommissionLimits();
			foreach ($list as &$singup_plan) {
				if ($singup_plan['commission_id'] != '1') {
					$singup_plan['option_value'] = implode(":", array($singup_plan['commission_id'], $singup_plan['commission_type'], $singup_plan['product_limit_id'], $singup_plan['duration'], $singup_plan['commission']));
				}
			}

			$json['singup_plans'] = $list;
			return $this->sendResponse($json);

		}else {
			$json["error"]		= "Only GET request method allowed";
			$json["success"]	= false;

			return $this->sendResponse($json);
		}
	}
}